//
//  CommonSwipMenu.swift
//  W_BAR_MAIN
//
//  Created by SK2 on 2017/9/17.
//  Copyright © 2017年 LC_WJH. All rights reserved.
//

import UIKit
import SnapKit

//常用滚动菜单
@IBDesignable
public class CommonSwipMenu:UIView{
   
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    
    public override init(frame: CGRect) {
        super.init(frame: frame)
        //refreshUI();
    }
  
    
    @IBInspectable public var check:Bool = false;
    
    ///标题列表
    @IBInspectable public var Titles:String = "示例1,示例2"{
        didSet{
            refreshUI();
        }
      //
    }
    
    
    @IBInspectable public var selectedFontSize:CGFloat = 15{
        didSet{
            refreshUI();
        }
    }
    @IBInspectable public var unselectedFontSize:CGFloat = 15{
        didSet{
            refreshUI();
        }
    }
    @IBInspectable public var selectedColor:UIColor = UIColor.white{
        didSet{
            refreshUI();
        }
    }
    @IBInspectable public var unselectedColor:UIColor = UIColor.gray{
        didSet{
            refreshUI();
        }
    }
    @IBInspectable public var gapColor:UIColor = UIColor.clear{
        didSet{
            refreshUI();
        }
    }
    
    
    
    
    ///下划线样式 -1 - 无 / 0 - 等宽 / 其他,自设长度
    @IBInspectable var underLineWidth:CGFloat = 0{
        didSet{
            refreshUI();
        }
    }
    @IBInspectable var underLineHeight:CGFloat = 2{
        didSet{
            refreshUI();
        }
    }
    
    
    var underStoryBoard = false;
 
    
    override public func prepareForInterfaceBuilder() {
        underStoryBoard = true;
        refreshUI();
    }
    
    
    
    
    public var theButtons:[UIButton] = [UIButton]();
    public var underLine:UIView?;
    
    
    public func refreshUI(){
        
        lastSelected = -1;
        underLine = nil;
        animationEnabled = false;
        
        for b:UIButton in theButtons{
            b.removeTarget(self, action: #selector(btTapHandler(_:)), for: UIControl.Event.touchUpInside);
        }
        theButtons.removeAll();
        
        for v in self.subviews{
            v.removeFromSuperview();
        }
        
        if Titles.utf8.count < 3{
            return;
        }
        
        let tA = Titles.components(separatedBy: ",");
        
        if tA.count < 1 {
            return;
        }
        
        let totalNum:Int  = tA.count;
       // let width:CGFloat   =   self.bounds.size.width / CGFloat(totalNum);
        
        
        for  i in 0 ..< totalNum {
            
           // let f:CGRect = CGRect.init(x: width * CGFloat(i), y: 0.0, width: width, height:  self.frame.size.height);
          //  let b:UIButton = UIButton.init(frame: f);
            
            let b:UIButton = UIButton.init();
            
            b.setTitle(tA[i], for: UIControl.State.normal);
            b.setTitleColor(UIColor.white, for: UIControl.State.normal);
            b.addTarget(self, action: #selector(btTapHandler(_:)), for: UIControl.Event.touchUpInside);
            
            self.addSubview(b);
            theButtons.append(b);
            
        }
        
        if theButtons.count > 0 {
            
            //修改使用autolayout布局
            //连接
            let o = self;
            var c = 0;
            var lastb:UIButton!;
            for b in theButtons {
                
                var insertGap = false;
                
                if c == 0{
                    //首
                    b.snp.makeConstraints({ (make) in
                        make.leading.equalTo(o.snp.leading);
                        make.top.equalTo(o.snp.top);
                        make.bottom.equalTo(o.snp.bottom);
                    });
                    
                    insertGap =  true;
                    
                }else if c == theButtons.count - 1 {
                    //尾
                    b.snp.makeConstraints({ (make) in
                        make.leading.equalTo(lastb.snp.trailing);
                        make.top.equalTo(o.snp.top);
                        make.bottom.equalTo(o.snp.bottom);
                        make.trailing.equalTo(o.snp.trailing);
                    });
                    
                }else{
                    //中
                    b.snp.makeConstraints({ (make) in
                        make.leading.equalTo(lastb.snp.trailing);
                        make.top.equalTo(o.snp.top);
                        make.bottom.equalTo(o.snp.bottom);
                    });
                    
                    insertGap =  true;
                }
                
                
                //插缝
                if insertGap {
                    let g = UIView.init();
                    self.addSubview(g);
                    g.snp.makeConstraints({ (make) in
                        make.width.equalTo(1);
                        make.top.equalTo(o.snp.top).offset(15);
                        make.bottom.equalTo(o.snp.bottom).offset(-15);
                        make.leading.equalTo(b.snp.trailing);
                    });
                    g.backgroundColor = gapColor;
                }
                
                
                
                
                lastb = b;
                c += 1;
                
            }
            //等宽
            let bts = theButtons;
            lastb.snp.makeConstraints({
                (make) in
                for b in bts {
                    make.width.equalTo(b.snp.width);
                }
            })
            
            self.layoutIfNeeded();
            selectBtAt(0);
            
        }
        
        
        
    }
    
    
    var animationEnabled:Bool = false;
    var lastSelected:Int = -1;
    
    func selectBtAt(_ idx:Int){
        
        if lastSelected == idx {
            return;
        }
        
        lastSelected = idx;
        tcb?(idx);
        
        if theButtons.count > 0  {
            for bt:UIButton in  theButtons{
                if bt == theButtons[idx]{
                    bt.titleLabel?.font =  UIFont.systemFont(ofSize: selectedFontSize);
                    bt.setTitleColor(selectedColor, for: UIControl.State.normal);
                }else{
                    bt.titleLabel?.font =  UIFont.systemFont(ofSize: unselectedFontSize);
                    bt.setTitleColor(unselectedColor, for: UIControl.State.normal);
                }
            }
            
            // -1 hidden 0 equleWidth >0 set
            if underLineWidth > -1 {
                if underLine == nil {
                    underLine = UIView.init();
                    underLine?.backgroundColor = selectedColor;
                    underLine?.layer.cornerRadius = 3;
                    addSubview(underLine!);
                    
                }
                
                //使用自动布局定位
                weak var wself = self;
                
                if  underLineWidth == 0 {
                    
                    underLine?.snp.remakeConstraints({
                        (make) in
                        
                        make.height.equalTo(wself!.underLineHeight);
                        make.bottom.equalTo(wself!.snp.bottom);
                        make.width.equalTo(wself!.theButtons[idx].snp.width);
                        make.centerX.equalTo(wself!.theButtons[idx].snp.centerX);
                        
                    })
                    
                }else{
                    
                    underLine?.snp.remakeConstraints({
                        (make) in
                        make.height.equalTo(wself!.underLineHeight);
                        make.bottom.equalTo(wself!.snp.bottom);
                        make.width.equalTo(wself!.underLineWidth);
                        make.centerX.equalTo(wself!.theButtons[idx].snp.centerX);
                    })
                }
                
                if underStoryBoard{
                    layoutIfNeeded();
                }else{
                    if animationEnabled {
                        UIView.animate(withDuration: 0.2, animations: {
                            wself?.layoutIfNeeded();
                        });
                    }else{
                        layoutIfNeeded();
                        weak var wself  = self;
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
                            wself?.animationEnabled = true;
                        });
                    }
                }
            }
        }
    }
    
    
    @objc func btTapHandler(_ sender:UIButton)->Void{
        for i in  0 ..< theButtons.count {
            if theButtons[i] == sender{
                selectBtAt(i);
                break;
            }
        }
    }
    
    
    //MARK:点击响应
    public  typealias TABCN = (Int)->Void;
    var tcb:TABCN?;
    
    public func setOnTapCb(cb:@escaping TABCN){
        tcb = cb;
    }
    
    
    
    
    
    
    
}
